import type { NormalizedLandmark } from '@mediapipe/tasks-vision'
import { BufferGeometry, Float32BufferAttribute } from 'three'
import { FACE_MESH_INDEX_BUFFER, FACE_MESH_UV } from '@/utils/face_geom'
export const transformLandamks = (landmarks: NormalizedLandmark[]) => {
  if (!landmarks) return landmarks
  //判断点位是否可信
  const hasvisibiliy = landmarks.find((i) => i.visibility)
  let minZ = 1e-4
  if (hasvisibiliy) {
    landmarks.forEach((landmark) => {
      // eslint-disable-next-line prefer-const
      let { z, visibility } = landmark
      z = -z //反转z轴在three中变为远处（越小越远）
      if (z < minZ && visibility) {
        minZ = z //找到小最远点
      }
    })
  } else {
    //反转z轴在three中变为远处（越小越远）找到最大，最近点
    minZ = Math.max(-landmarks[234].z, -landmarks[454].z)
  }
  return landmarks.map((landmark) => {
    const { x, y, z } = landmark
    return {
      x: -0.5 + x, //将x轴的0 - 1转为-0.5 - 0.5         x - 0.5
      y: 0.5 - y, //将y轴的0 - 1转为-0.5 - 0.5并反转  -(y - 0.5)
      z: -z - minZ,
      visibility: landmark.visibility,
    }
  })
}
export const scaleLandmark = (landmark: NormalizedLandmark, width: number, height: number) => {
  const { x, y, z } = landmark
  return {
    ...landmark,
    x: x * width,
    y: y * height,
    z: z * width,
  }
}
export const makeGeometry = (landmarks: NormalizedLandmark[]) => {
  const geometry = new BufferGeometry()
  const vertices = []
  const uvs = []

  for (let i = 0; i < 468; i++) {
    const { x, y, z } = landmarks[i]
    const vertex = [x, y, z]
    vertices.push(...vertex)
  }
  const skipIndices = new Set([21, 71, 163, 139, 127, 34, 251, 301, 389, 368, 356, 264]) // 比如耳朵点
  const oldToNew: { [key: number]: number } = {}
  const newVertices: number[] = []
  landmarks.forEach((l, i) => {
    if (!skipIndices.has(i)) {
      oldToNew[i] = newVertices.length / 3 // 新索引
      newVertices.push(l.x, l.y, l.z)
    }
  })

  // 过滤索引
  const newIndices = []
  for (let i = 0; i < FACE_MESH_INDEX_BUFFER.length; i += 3) {
    const a = FACE_MESH_INDEX_BUFFER[i],
      b = FACE_MESH_INDEX_BUFFER[i + 1],
      c = FACE_MESH_INDEX_BUFFER[i + 2]
    if (skipIndices.has(a) || skipIndices.has(b) || skipIndices.has(c)) continue // 三角形里有删除点 → 跳过
    newIndices.push(oldToNew[a], oldToNew[b], oldToNew[c])
  }

  for (let j = 0; j < 468; j++) {
    uvs[j * 2] = FACE_MESH_UV[j][0]
    uvs[j * 2 + 1] = FACE_MESH_UV[j][1]
  }
  geometry.setIndex(newIndices)
  geometry.setAttribute('position', new Float32BufferAttribute(newVertices, 3))
  // geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2))
  geometry.computeVertexNormals()
  return geometry
}
